package com.shanhai.wallpapers.fragments.wallpapers

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.core.graphics.toColorInt
import androidx.paging.PagingDataAdapter
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.shanhai.wallpapers.databinding.ItemWallpaperBinding
import com.shanhai.wallpapers.network.response.Photo

class WallpaperAdapter(private val itemClickListener: (photo: Photo) -> Unit) :
    PagingDataAdapter<Photo, WallpaperAdapter.WallPaperViewHolder>(
        WALLPAPER_COMPARATOR
    ) {
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): WallPaperViewHolder {
        return WallPaperViewHolder(
            ItemWallpaperBinding.inflate(
                LayoutInflater.from(parent.context),
                parent,
                false
            )
        )
    }

    override fun onBindViewHolder(holder: WallPaperViewHolder, position: Int) {
        getItem(position)?.let { photo ->
            holder.bind(photo)
        }
    }

    inner class WallPaperViewHolder(
        private val binding: ItemWallpaperBinding
    ) : RecyclerView.ViewHolder(binding.root) {
        fun bind(photo: Photo) {
            binding.imageWallpaper.apply {
                photo.avgColor?.toColorInt()?.let {
                    setBackgroundColor(it)
                }
                photo.source?.large?.let { url ->
                    Glide.with(itemView)
                        .load(url)
                        .transition(DrawableTransitionOptions.withCrossFade(300))
                        .into(this)
                }
                setOnClickListener {
                    itemClickListener.invoke(photo)
                }
            }
        }
    }

    companion object {
        private val WALLPAPER_COMPARATOR = object : DiffUtil.ItemCallback<Photo>() {
            override fun areItemsTheSame(oldItem: Photo, newItem: Photo): Boolean {
                return oldItem.id == newItem.id
            }

            override fun areContentsTheSame(oldItem: Photo, newItem: Photo): Boolean {
                return oldItem == newItem
            }
        }
    }
}